package com.soushangxing.comfyuibackendv2.service

import com.soushangxing.comfyuibackendv2.bean.ResponseType
import com.soushangxing.comfyuibackendv2.repository.ModelRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.web.multipart.MultipartFile
import java.util.UUID

@Service
class ComfyUIModelService {
    @Autowired
    lateinit var modelRepository: ModelRepository

    @Autowired
    lateinit var fileService: FileService

    @Autowired
    lateinit var queueService: GlobalQueueService

    /**
     * 入口：根据type参数分配指定的处理服务。
     * 由于每个服务的入参、替换内容可能不同，以本函数为校验和调度。
     */
    suspend fun dispatch(taskId:String=UUID.randomUUID().toString(), userId: String, type:String, file: MultipartFile?,
                 positive:String?, negative:String?, denoise: String?): ResponseType{
        var denoiseParam = denoise
        if (denoise.isNullOrEmpty()) {
            denoiseParam = "0.5"
        }
        return if (type == "guofeng") {
            guofengV1(taskId,userId,file!!,positive,negative,denoiseParam)
        } else if (type == "text2image-basic") {
            basicText2image(taskId,userId,positive,negative,denoiseParam)
        } else {
            universalRepaint(type, taskId,userId,file!!,positive,negative,denoiseParam)
        }
    }


    /**
     * 人物图片转国风美女
     */
    suspend fun guofengV1(taskId:String, userId: String, file: MultipartFile, positive:String?=null, negative:String?=null,
                          denoise:String?) : ResponseType {
        try{
            // 上传原图片
            val uploadResponse = fileService.saveFile(file) ?: return ResponseType("上传图片失败")

            // 获取图片的URL
            val imageUrl = uploadResponse.path

            // 获取模型模板
            val model = modelRepository.findFirstByTypeCode("guofeng")!!

            var prompt = "{\n" +
                    "\"client_id\":\"*@#client_id#@*\"," +
                    "\"prompt\":" + model.prompt + "}"

            prompt = prompt.replace("*@#IMAGE1#@*",imageUrl)
            prompt = prompt.replace("*@#POSITIVE#@*",positive?:"")
            prompt = prompt.replace("*@#NEGATIVE#@*",negative?:"")
            prompt = prompt.replace("*@#DENOISE#@*",denoise?:"0.5")


//            return comfyUIService.queuePrompt(taskId, userId, prompt)
            return queueService.backendQueue(taskId, userId, prompt)
        } catch (e:Exception){
            return ResponseType("国风V1运行失败:"+e.message)
        }
    }

    /**
     * 基础文生图
     */
    suspend fun basicText2image(taskId:String, userId: String, positive:String?=null, negative:String?=null,
                                denoise:String?) : ResponseType{


        // 获取模型模板
        val model = modelRepository.findFirstByTypeCode("text2image-basic")!!

        var prompt = "{\n" +
                "\"client_id\":\"*@#client_id#@*\"," +
                "\"prompt\":" + model.prompt + "}"

        prompt = prompt.replace("*@#POSITIVE#@*",positive?:"")
        prompt = prompt.replace("*@#NEGATIVE#@*",negative?:"")
        prompt = prompt.replace("*@#DENOISE#@*",denoise?:"0.5")

//        return comfyUIService.queuePrompt(taskId,userId, prompt)
        return queueService.backendQueue(taskId, userId, prompt)
    }


    /**
     * 通配调用【重绘】，要求必须有一个图，其他可选
     */
    suspend fun universalRepaint(type:String, taskId:String, userId: String, file: MultipartFile,positive:String?=null, negative:String?=null,
                                denoise:String?) : ResponseType{

        // 获取模型模板
        val model = modelRepository.findFirstByTypeCode(type)
        if (model==null){
            return ResponseType("暂不支持此类调用")
        }

        // 上传原图片
        val uploadResponse = fileService.saveFile(file) ?: return ResponseType("上传图片失败")

        // 获取图片的URL
        val imageUrl = uploadResponse.path

        var prompt = "{\n" +
                "\"client_id\":\"*@#client_id#@*\"," +
                "\"prompt\":" + model.prompt + "}"

        prompt = prompt.replace("*@#IMAGE1#@*",imageUrl)
        prompt = prompt.replace("*@#POSITIVE#@*",positive?:"")
        prompt = prompt.replace("*@#NEGATIVE#@*",negative?:"")
        prompt = prompt.replace("*@#DENOISE#@*",denoise?:"0.5")

        return queueService.backendQueue(taskId, userId, prompt)
    }
}
